import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Ap0stoL2
 * Date: 2023-07-29
 * Time: 8:16
 */
//生产消费者模型
public class Demo19 {
    public static void main(String[] args) {
        //搞一个阻塞队列,作为交易场所
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();

        //负责生产元素
        Thread t1 = new Thread(()->{
           int count=0;
           while(true){
               try {
                   queue.put(count);
                   System.out.println("生产者元素添加 ="+count);//答应在添加后
                   count++;

                   Thread.sleep(1000);

               } catch (InterruptedException e) {
                   e.printStackTrace();
               }

           }
        });


        //负责消费
        Thread t2 = new Thread(()->{
           while(true){
               try {
                   //这里不需要sleep也可以让生产那跟着消费走,且互不影响
                   Integer n =  queue.take();
                   System.out.println("消费元素 ="+ n);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });

        t1.start();
        t2.start();
    }
}
